﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Linq.Extensions;
using Abp.Localization;
using Abp.Runtime.Session;
using Abp.UI;
using WorkflowCoreDockingDemo.Authorization;
using WorkflowCoreDockingDemo.Authorization.Accounts;
using WorkflowCoreDockingDemo.Authorization.Roles;
using WorkflowCoreDockingDemo.Authorization.Users;
using WorkflowCoreDockingDemo.Roles.Dto;
using WorkflowCoreDockingDemo.Users.Dto;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Abp.Web.Models;
using Microsoft.AspNetCore.Authorization;
using WorkflowCoreDockingDemo.Roles;
using Microsoft.AspNetCore.Mvc;
using WorkflowCoreDockingDemo.CustomForm.LeaveForms.Dto;
using WorkflowCoreDockingDemo.CustomForm;
using Abp.AutoMapper;
using Abp.ObjectMapping;

namespace WorkflowCoreDockingDemo.Users
{
    [AbpAuthorize(PermissionNames.Pages_CustomForms)]
    public class LeaveFormAppService : AsyncCrudAppService<LeaveForm, LeaveFormDto, long, PagedResultRequestDto, CreateLeaveFormDto, UpdateLeaveFormDto>, ILeaveFormAppService
    {
        private readonly IRepository<LeaveForm, long> repository;
        private  readonly IObjectMapper mapper;

        public LeaveFormAppService(IRepository<LeaveForm, long> repository, IObjectMapper mapper) : base(repository)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        public override async Task<LeaveFormDto> CreateAsync(CreateLeaveFormDto input)
        {
            var leaveForm = new LeaveForm(input.Days, input.Reason, input.Memo);
            leaveForm = repository.Insert(leaveForm);
            return mapper.Map<LeaveFormDto>(leaveForm);
        }

        public override async Task<LeaveFormDto> UpdateAsync(UpdateLeaveFormDto input)
        {

            var entity =  repository.Get(input.Id);
            if(entity == null)
            {
                return null;
            }
            if(!entity.IsEditable())
            {
                throw new UserFriendlyException("当前状态无法编辑");
            }
            entity.Update(input.Days, input.Reason, input.Memo);
            repository.Update(entity);
            return mapper.Map<LeaveFormDto>(entity);
        }

        public override async Task DeleteAsync(EntityDto<long> input)
        {
            var entity = repository.Get(input.Id);
            if (entity == null)
            {
                return ;
            }
            if (!entity.IsEditable())
            {
                throw new UserFriendlyException("当前状态无法编辑");
            }
            await base.DeleteAsync(input);
        }
    }
}

